<template>
    <div class="drag-container">
        <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
            全选
        </el-checkbox>
        <el-checkbox-group v-model="prop.option.checkitems" @change="handleCheckedCitiesChange">
            <el-checkbox-button v-for="(item, i) in prop.option.allitems" :key="item" :label="item" :value="item"
                draggable="true" @dragstart="dragstart($event, i)" @dragenter="dragenter($event, i)" @dragend="dragend"
                @dragover="dragover">
                {{ item }}
            </el-checkbox-button>
        </el-checkbox-group>
    </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
const prop = defineProps<{
    option: any;
}>();

let dragIndex = 0
const checkAll = ref(false);
const isIndeterminate = ref(true);

//全选按钮相关
const handleCheckAllChange = (val: boolean) => {
    prop.option.checkitems = val ? prop.option.allitems : [];
    isIndeterminate.value = false;
}

const handleCheckedCitiesChange = (value: string[]) => {
    const checkedCount = value.length
    checkAll.value = checkedCount === prop.option.allitems.length
    isIndeterminate.value = checkedCount > 0 && checkedCount < prop.option.allitems.length
}


//拖拽相关函数
function dragstart(e: any, index: number) {
    e.stopPropagation()
    dragIndex = index
    setTimeout(() => {
        e.target.classList.add('moveing')
    }, 0)
}
function dragenter(e: any, index: number) {
    e.preventDefault()
    // 拖拽到原位置时不触发
    if (dragIndex !== index) {
        const source = prop.option.allitems[dragIndex];
        prop.option.allitems.splice(dragIndex, 1);
        prop.option.allitems.splice(index, 0, source);
        // 更新节点位置
        dragIndex = index
    }
}
function dragover(e: any) {
    e.preventDefault()
    e.dataTransfer.dropEffect = 'move'
}
function dragend(e: any) {
    e.target.classList.remove('moveing')
}
</script>

<style scoped>
.drag-container {
    padding: 20px;
}

.moveing {
    opacity: 0;
}
</style>
